package com.tianzhu.config;

import java.util.Date;
import java.util.List;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.authentication.rememberme.PersistentRememberMeToken;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import com.tianzhu.domain.PersistentLogin;
import com.tianzhu.repositories.PersistentLoginRepo;

@Slf4j
public class SpringDataTokenRepositoryImpl implements PersistentTokenRepository {

    @Autowired
    PersistentLoginRepo rememberMeTookenRepository;

    @Override
    public void createNewToken(PersistentRememberMeToken token) {
    	PersistentLogin rememberMeToken = new PersistentLogin(token.getUsername(), token.getSeries(), token.getTokenValue(), token.getDate());
        rememberMeTookenRepository.save(rememberMeToken);
    }

    @Override
    public void updateToken(String series, String tokenValue, Date lastUsed) {
    	PersistentLogin rememberMeToken = rememberMeTookenRepository.findBySeries(series);
        rememberMeToken.setToken(tokenValue);
        rememberMeToken.setLastUsed(lastUsed);
        rememberMeTookenRepository.save(rememberMeToken);
    }

    @Override
    public PersistentRememberMeToken getTokenForSeries(String series) {
    	PersistentLogin rememberMeToken = rememberMeTookenRepository.findBySeries(series);
        if (rememberMeToken == null) {
            log.debug("No remember me token for series '{}' was found.", series);
            return null;
        }
        return new PersistentRememberMeToken(rememberMeToken.getUsername(), rememberMeToken.getSeries(), rememberMeToken.getToken(), rememberMeToken.getLastUsed());
    }

    @Override
    public void removeUserTokens(String username) {
        List<PersistentLogin> rememberMeTookens = rememberMeTookenRepository.findByUsername(username);
        for (PersistentLogin rememberMeToken : rememberMeTookens) {
            rememberMeTookenRepository.delete(rememberMeToken);
        }
    }

}
